from django.shortcuts import render
from rest_framework.viewsets import ModelViewSet
from .models import *
from .serializers import *
from rest_framework.response import Response
from goods.serializer import *
# Create your views here.
#订单信息视图集
class OrderInfoViewSet(ModelViewSet):
    queryset = OrderInfo.objects.all()
    serializer_class = OrderInfoSer
    lookup_field = 'pk'
    lookup_url_kwarg = 'pk'
    #重写list
    def my_list(self, request, *args, **kwargs):
        orders = self.get_queryset()
        orders_ser = self.get_serializer(orders,many=True)
        temp = []
        for per_order in orders_ser.data:
            #获取订单对象
            per_order_obj = orders.filter(order_id=per_order.get('order_id')).first()
            #反向查询当前订单中的所有商品
            current_order_goods = per_order_obj.order_goods.all()
            #序列化当前订单中所有商品
            current_order_goods_ser = OrderGoodsSer(current_order_goods,many=True)
            #处理所有的订单商品
            temp2 = []
            for per_order_good in current_order_goods_ser.data:
                #获取当前订单商品对象
                per_order_good_obj = OrderGoods.objects.filter(id=per_order_good.get('id')).first()
                #对查询到的商品对象进行序列化
                sku_dict = SKUSer(per_order_good_obj.sku).data
                per_order_good['sku'] = sku_dict
                #吧处理完的数据加到temp2里
                temp2.append(per_order_good)
            #添加skus
            per_order['skus'] = temp2
            temp.append(per_order)
        my_data = {}
        return temp

    #重写retrieve
    def retrieve(self, request,pk, *args, **kwargs):
        all_orders = self.my_list(request,pk,*args,**kwargs)
        print("所有的订单数据：",all_orders)
        for i in all_orders:
            if i.get('order_id') == pk:
                return Response(i)
        return Response({'code':'400','msg':'订单数据不存在'})

    #重写update
    def update(self, request,pk, *args, **kwargs):
        order = self.get_queryset().filter(order_id=pk).first()
        status = request.data.get('status')

        order.status = status
        order.save()
        return Response({'code':'200','msg':'更新订单状态成功'},status=200)